package com.mvp.lt.airlineview.utils;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadUtil {

    private BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>();
    private ExecutorService executorService = null;


    private volatile static ThreadUtil instance;

    public static ThreadUtil getInstance() {
        if (instance == null) {
            synchronized (ThreadUtil.class) {
                if (instance == null) {
                    instance = new ThreadUtil();
                }
            }
        }
        return instance;
    }


    public static void destroy() {
        if (instance != null) {
            instance.executorService.shutdownNow();
            instance.executorService = null;
            instance = null;
        }
    }

    private ThreadUtil() {
        // 获得当前CPU的核心数
        int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
        int KEEP_ALIVE_TIME = 1;
        // 设置线程池的核心线程数2-4之间,但是取决于CPU核数
        int CORE_POOL_SIZE = Math.max(2, Math.min(NUMBER_OF_CORES - 1, 4));
        TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
        executorService = new ThreadPoolExecutor(CORE_POOL_SIZE,
                CORE_POOL_SIZE,
                KEEP_ALIVE_TIME,
                KEEP_ALIVE_TIME_UNIT,
                taskQueue,
                new ThreadPoolExecutor.AbortPolicy());
    }


    public void execute(Runnable command) {
        if (executorService != null) {
            executorService.execute(command);
        }
    }
    public static void runOnUiThread(Runnable r) {
        if (isMainThread()) {
            r.run();
        } else {
            LazyHolder.sUiThreadHandler.post(r);
        }
    }

    public static void runOnUiThread(Runnable r, long delay) {
        LazyHolder.sUiThreadHandler.postDelayed(r, delay);
    }

    public static void removeCallbacks(Runnable r) {
        LazyHolder.sUiThreadHandler.removeCallbacks(r);
    }

    private static boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }

    private static class LazyHolder {
        private static Handler sUiThreadHandler = new Handler(Looper.getMainLooper());
    }
    /**
     * 获取在新线程运行的Handler对象。
     *
     * @return 在新线程运行的Handler对象。
     */
    public static Handler getNewHandlerInOtherThread() {
        HandlerThread handlerThread = new HandlerThread(System.currentTimeMillis() + "");
        handlerThread.start();
        return new Handler(handlerThread.getLooper());
    }
}
